<template>
  <div>
    <el-dialog
      title="设置字段"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="60%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      :destroy-on-close="true"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段类型" prop="fieldType">
              <el-radio-group v-model="form.fieldType" :disabled="isBase">
                <el-radio
                  v-for="item in fieldTypeOptions"
                  :key="item.codevalue"
                  :label="item.codevalue"
                  @change="handleFieldTypeChange"
                  >{{ item.codename }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段编码" prop="fieldCode">
              <el-input
                v-model="form.fieldCode"
                type="text"
                placeholder="请输入字段编码"
                :disabled="form.fieldType == '1' || isBase"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 字段类型：指标 -->
        <template v-if="form.fieldType == '1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="关联指标" prop="associativePointerName">
                <el-input
                  type="text"
                  v-model="form.associativePointerName"
                  readonly
                  :disabled="isBase"
                  placeholder="请选择关联指标"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="handleOpenIndexList"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认值" prop="defaultValue">
                <el-input
                  v-model="form.defaultValue"
                  type="text"
                  placeholder="请输入默认值"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- 字段类型：自定义 -->
        <template v-if="form.fieldType != '1'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="组件类型" prop="componentType">
                <el-select
                  v-model="form.componentType"
                  placeholder="请选择组件类型"
                  clearable
                  filterable
                  :disabled="isBase"
                  @change="handleComponentTypeChange"
                >
                  <el-option
                    v-for="item in dict.componentType"
                    :key="item.codevalue"
                    :label="item.codename"
                    :value="item.codevalue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="form.componentType == 'onlyread'" :span="12">
              <el-form-item label="标签值" prop="fieldName">
                <el-input
                  v-model="form.fieldName"
                  type="text"
                  placeholder="请输入标签值"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-else :span="12">
              <el-form-item label="是否必填" prop="isRequested">
                <el-radio-group v-model="form.isRequested" :disabled="isBase">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- 组件类型：单选、多选 -->
        <template
          v-if="
            ['singleSelect', 'radio', 'multipleSelect', 'checkbox'].includes(
              form.componentType
            )
          "
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="选项设置" prop="optionSetting">
                <div
                  v-for="(item, i) in form.optionSetting"
                  :key="i"
                  class="item-list"
                >
                  <el-input
                    v-model="item.itemvalue"
                    :disabled="isBase"
                  ></el-input>
                  <el-checkbox
                    v-model="item.isDefault"
                    @change="handleSingleSelectDefaultChange(item, i)"
                    >默认勾选</el-checkbox
                  >
                  <el-checkbox
                    v-model="item.isAlarm"
                    @change="handleSetIsAlarm()"
                    >设为异常告警</el-checkbox
                  >
                  <el-button
                    v-if="form.optionSetting.length > 1"
                    :disabled="isBase"
                    type="text"
                    @click="handleDeleteOptionSetting(item)"
                    >移除</el-button
                  >
                </div>
                <div>
                  <el-button
                    type="text"
                    :disabled="isBase"
                    @click="handleAddOptionSetting"
                    >添加选项</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- 组件类型：文本框、数值 -->
        <template v-if="['text', 'number'].includes(form.componentType)">
          <el-row>
            <el-col :span="12">
              <el-form-item label="默认值" prop="defaultValue">
                <el-input
                  v-model="form.defaultValue"
                  type="text"
                  placeholder="请输入默认值"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="异常告警" prop="warnType">
                <div class="form-item-content-box">
                  <el-select
                    v-model="form.warnType"
                    placeholder="请选择异常告警条件"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in dict.warnType"
                      :key="item.codevalue"
                      :label="item.codename"
                      :value="item.codevalue"
                    >
                    </el-option>
                  </el-select>
                  <el-input
                    v-model="form.warnValue"
                    type="text"
                    :placeholder="
                      ['7', '8', '9', '10', '11'].includes(form.warnType)
                        ? '区间值n,m英文逗号分隔'
                        : '请输入告警值'
                    "
                    clearable
                  ></el-input>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- 组件类型：日期、日期时间 -->
        <template v-if="['date', 'datetime'].includes(form.componentType)">
          <el-row>
            <el-col :span="24">
              <el-form-item label="默认值" prop="defaultValue">
                <el-checkbox
                  v-model="form.defaultValue"
                  true-label="currentDateTime"
                  >当前{{ componentTypeMap[form.componentType] }}</el-checkbox
                >
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 指标列表 -->
    <IndexList
      :visible.sync="indexListDialog.visible"
      :defaultValues="indexListDialog.defaultValues"
      :defaultSearch="indexListDialog.defaultSearch"
      :multiple="false"
      @closeDialog="handleIndexListClose"
    ></IndexList>
  </div>
</template>
<script>
import IndexList from "@/views/components/indexList";
export default {
  components: { IndexList },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    col: {
      type: Object,
      default: null,
    },
    taskTemplateDetail: {
      type: Object,
      default: null,
    },
  },
  dicts: ["fieldType", "componentType", "warnType"],
  data() {
    return {
      form: {
        fieldName: null,
        fieldType: "2", //默认选中自定义
        associativePointer: null,
        associativePointerName: null,
        fieldCode: null,
        defaultValue: null,
        componentType: null,
        isRequested: "1", //默认必选
        optionSetting: [], // 默认至少一个选项
        warnType: "",
        warnValue: "",
      },
      rules: {
        fieldName: [
          { required: true, message: "请输入", trigger: "change" },
          { max: 30, message: "字段名称长度最多30个字符", trigger: "change" },
        ],
        fieldType: [
          { required: true, message: "请选择字段类型", trigger: "change" },
        ],
        associativePointerName: [
          { required: true, message: "请选择关联指标", trigger: "change" },
        ],
        fieldCode: [
          { required: true, message: "请输入字段编码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (this.form.fieldType == "1") {
                // 指标类
                callback();
              } else if (value?.length > 30) {
                // 自定义
                callback(new Error("字段编码长度最多30个字符"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        defaultValue: [
          { max: 30, message: "默认值长度最多30个字符", trigger: "change" },
        ],
        componentType: [
          { required: true, message: "请选择组件类型", trigger: "change" },
        ],
        isRequested: [
          { required: true, message: "请选择是否必选", trigger: "change" },
        ],
        optionSetting: [
          { required: true, message: "请配置选项设置", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              // 至少要有一个选项值
              if (!value?.length) {
                callback(new Error("请至少配置一个选项设置"));
                return;
              }
              // 选项值不能为空
              const index = value.findIndex(
                (ele) => !ele.itemvalue || !ele.itemvalue.trim()
              );
              if (index != -1) {
                callback(new Error("请配置选项设置"));
                return;
              }
              // 选项值不能重复
              const allItemvalues = value.map((ele) => ele.itemvalue.trim());
              const unrepeats = new Set(allItemvalues);
              if (unrepeats.size < allItemvalues.length) {
                callback(new Error("选项值不能重复"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      // 指标选择弹框
      indexListDialog: {
        visible: false,
        defaultValues: [],
        defaultSearch: {},
      },
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    fieldTypeOptions() {
      if (!this.taskTemplateDetail?.associatedDevice && this.dict.fieldType) {
        // 若模板未关联“设备”，则不提供“指标类”选项。
        return this.dict.fieldType.filter((ele) => ele.codevalue != "1");
      }
      return this.dict.fieldType;
    },
    isBase() {
      if (this.row && this.col?.prop) {
        return this.row[this.col.prop].fieldSource == "base";
      }
      return false;
    },
    componentTypeMap() {
      return this.dictToMap(this.dict.componentType);
    },
  },
  created() {},
  methods: {
    handleClose() {
      this.resetForm();
    },
    handleOpen() {
      if (this.row) {
        const formFieldObj = this.row[this.col.prop];
        if (!formFieldObj) {
          this.resetForm();
          return;
        }
        this.form = {
          fieldName: formFieldObj.fieldName || null,
          fieldType: formFieldObj.fieldType || "2",
          associativePointer: formFieldObj.associativePointer || null,
          associativePointerName: formFieldObj.associativePointerName || null,
          fieldCode: formFieldObj.fieldCode || null,
          defaultValue: formFieldObj.defaultValue || null,
          componentType: formFieldObj.componentType || null,
          isRequested: formFieldObj.isRequested || "1",
          optionSetting: formFieldObj.optionSetting || [],
          warnType: formFieldObj.warnType || "",
          warnValue: formFieldObj.warnValue || "",
        };
      }
    },
    // 字段类型切换
    handleFieldTypeChange(value) {
      // 重置部分字段到初始化状态
      this.form.associativePointer = null;
      this.form.associativePointerName = null;
      this.form.fieldCode = null;
      this.form.defaultValue = null;
      this.form.componentType = null;
      this.form.isRequested = "1";
      this.form.optionSetting = [];
      this.form.warnType = "";
      this.form.warnValue = "";
      this.form.fieldName = ""; //标签值
    },
    // 打开关联指标弹窗
    handleOpenIndexList() {
      const { associativePointer, associativePointerName } = this.form;
      if (associativePointer) {
        this.indexListDialog.defaultValues = [
          { id: associativePointer, indexConfigName: associativePointerName },
        ];
      } else {
        this.indexListDialog.defaultValues = [];
      }
      this.indexListDialog.defaultSearch = {
        equipId: this.taskTemplateDetail
          ? this.taskTemplateDetail.associatedDevice
          : null,
        indexMetaDto: {
          indexType: "ED",
        },
      };
      this.indexListDialog.visible = true;
    },
    handleIndexListClose(list) {
      if (!list?.length) {
        return;
      }
      this.form.associativePointer = list[0].id;
      this.form.associativePointerName = list[0].indexConfigName;
      this.form.fieldCode = list[0].indexConfigCode;
    },
    // 组件类型切换
    handleComponentTypeChange(value) {
      // 重置部分字段到初始化状态
      this.form.defaultValue = null;
      this.form.optionSetting = [];
      this.form.warnType = "";
      this.form.warnValue = "";
      this.form.fieldName = ""; //标签值
    },
    // 添加选项设置
    handleAddOptionSetting() {
      const id = new Date().getTime().toString();
      this.form.optionSetting.push({
        id,
        itemvalue: "",
        isAlarm: false,
      });
    },
    // 单选/多选字段，勾选默选中项
    handleSingleSelectDefaultChange(item, index) {
      // 多选字段不需要清除
      if (["multipleSelect", "checkbox"].includes(this.form.componentType)) {
        return;
      }
      this.form.optionSetting.forEach((ele, i) => {
        if (index != i) {
          this.$set(this.form.optionSetting[i], "isDefault", false);
        }
      });
    },
    // 移除选项设置
    handleDeleteOptionSetting(item) {
      // 至少有一个选项
      if (this.form.optionSetting.length <= 1) {
        this.msgWarning("选项设置必须至少有一个");
        return;
      }
      const delIndex = this.form.optionSetting.findIndex(
        (ele) => ele.id === item.id
      );
      if (delIndex == -1) {
        return;
      }
      this.form.optionSetting.splice(delIndex, 1);
    },
    // 设置为告警（设置选项时）
    handleSetIsAlarm() {
      const alarmItems = this.form.optionSetting.filter((ele) => !!ele.isAlarm);
      this.form.warnValue = alarmItems.map((ele) => ele.itemvalue).join(",");
      this.form.warnType = "1"; //设置为等于
    },
    handleSubmit() {
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          // 单选/多选时，配置选项的默认值
          if (
            ["multipleSelect", "checkbox", "singleSelect", "radio"].includes(
              this.form.componentType
            )
          ) {
            this.form.defaultValue = this.form.optionSetting
              .filter((ele) => !!ele.isDefault)
              .map((ele) => ele.itemvalue)
              .join(",");
          }
          const param = { ...this.form };
          this.$emit("refresh", this.row, this.col, param);
          this.msgSuccess("保存成功！");
          this.dialogVisible = false;
        }
      });
    },
    resetForm() {
      this.form = {
        fieldName: null,
        fieldType: "2", //默认选中自定义
        associativePointer: null,
        associativePointerName: null,
        fieldCode: null,
        defaultValue: null,
        componentType: null,
        isRequested: "1", //默认必选
        optionSetting: [],
        warnType: "",
        warnValue: "",
      };
      this.$refs.ruleForm?.clearValidate();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select,
.el-input-number {
  width: 100%;
}
.item-list {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 10px;
  gap: 20px;
  .el-radio,
  .el-checkbox {
    margin-right: 0;
  }
  .el-input {
    width: 150px;
  }
}
.form-item-content-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  .el-select {
    flex: 2;
  }
  .el-input {
    flex: 3;
  }
}
</style>
